from airtest.core.api import *
from airtest.core.error import TargetNotFoundError
import time
import logging
from config.constants import SNAPSHOT_PATH


class AirtestUtils:
    """Airtest 基础工具封装"""
    @staticmethod
    def connect_device(device_uri):
        """连接设备"""
        try:
            connect_device(device_uri)
            logging.info(f"✅ 设备已连接: {device_uri}")
        except Exception as e:
            raise Exception(f"❌ 设备连接失败: {str(e)}")


    @staticmethod
    def start_app(package_name):
        """启动应用"""
        start_app(package_name)
        time.sleep(5)  # 等待启动
        logging.info(f"✅ 应用已启动: {package_name}")

    @staticmethod
    def stop_app(package_name):
        """停止应用"""
        stop_app(package_name)
        logging.info(f"✅ 应用已关闭: {package_name}")

    @staticmethod
    def assert_png(template_path, threshold=0.7, timeout=10, action_name="元素"):
        """断言元素（封装重试、日志）"""
        template = Template(template_path, threshold=threshold)
        try:
            if wait(template, timeout=timeout):
                return True
            raise TargetNotFoundError(f"超时未找到 {action_name}")
        except Exception as e:
            raise Exception(f"❌ 断言失败: {action_name}, 原因: {str(e)}")

    @staticmethod
    def click_element(template_path, threshold=0.7, timeout=10, action_name="元素"):
        """点击元素（封装重试、日志）"""
        template = Template(template_path, threshold=threshold)
        try:
            if wait(template, timeout=timeout):
                touch(template)
                time.sleep(2)
                logging.info(f"✅ 成功点击: {action_name}")
                return True
            raise TargetNotFoundError(f"超时未找到 {action_name}")
        except Exception as e:
            raise Exception(f"❌ 点击失败: {action_name}, 原因: {str(e)}")

    @staticmethod
    def input_text(template_path, text, threshold=0.6, action_name="输入框"):
        """输入文本（先点击激活，再输入）"""
        AirtestUtils.click_element(template_path, threshold, action_name=action_name)
        text(text)
        time.sleep(1)
        logging.info(f"✅ 已输入: {text} 到 {action_name}")

    @staticmethod
    def clear_and_input_text(template_path, new_text, threshold=0.6, action_name="输入框"):
        """
        清除输入框原有内容并输入新内容
        :param template_path: 输入框模板路径（用于定位输入框）
        :param new_text: 要输入的新内容
        :param threshold: 图像匹配阈值，默认 0.6
        :param action_name: 输入框名称（用于日志打印）
        """
        # 1. 先点击输入框，激活输入状态
        AirtestUtils.click_element(template_path, threshold, action_name=action_name)
        time.sleep(1)  # 等待输入框激活

        # 2. 通过连续输入退格键（Backspace）的方式清除原有内容
        #    这里假设输入框内容长度不会超过 50 个字符，可根据实际情况调整循环次数
        for _ in range(50):
            keyevent("KEYCODE_DEL")  # Airtest 发送删除键事件
            time.sleep(0.1)  # 避免操作过快

        # 3. 输入新内容
        text(new_text)
        time.sleep(1)
        logging.info(f"✅ 已清除 {action_name} 原有内容并输入: {new_text}")

    @staticmethod
    def snapshot_on_error():
        """错误时自动截图"""
        filename = f"{SNAPSHOT_PATH}\error_{int(time.time())}.png"
        snapshot(msg="错误截图", filename=filename)
        logging.info(f"📸 错误截图已保存: {filename}")